using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace SerialPortProfileApplication
{
    public partial class Form1 : Form
    {
        SerialPort sp = null;
        string displayString = "";
        string error = "";

        public Form1()
        {
            InitializeComponent();
            btnSend.Enabled = false;
        }

        private void btnSet_Click(object sender, EventArgs e)
        {
            try
            {

                if (string.IsNullOrEmpty(cmbPortName.Text))
                {
                    MessageBox.Show("Please enter a valid Port name for e.g. COM1", "Legacy Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    cmbPortName.Focus();
                }
                else
                {
                    sp = new SerialPort(cmbPortName.Text);
                    sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
                    sp.ErrorReceived += new SerialErrorReceivedEventHandler(sp_ErrorReceived);
                    sp.Open();
                    btnSet.Enabled = false;
                    cmbPortName.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                string errMessage = "";

                if (ex.InnerException != null)
                    errMessage = ex.Message + ex.InnerException.Message;
                else
                    errMessage = ex.Message;

                MessageBox.Show(errMessage, "Legacy Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
                btnSet.Enabled = true;
                cmbPortName.Text = string.Empty;
            }
        }

        void sp_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
        {
            error = sp.ReadExisting();
            this.Invoke(new EventHandler(SetErrorText));
        }

        void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            displayString = sp.ReadExisting();
            this.Invoke(new EventHandler(DisplayReceiveData));
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            if (sp != null)
                if (sp.IsOpen)
                    sp.Close();
            Dispose();
        }


        private void btnSend_Click(object sender, EventArgs e)
        {
            if (sp == null)
            {
                MessageBox.Show("Please connect to the serial port before sending data.",
                    "Legacy Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                if (txtBoxLegacyApp.Text != "")
                {
                    sp.WriteLine(txtBoxLegacyApp.Text);
                    txtBoxLegacyAppSent.Text += "> " + txtBoxLegacyApp.Text.Trim() + Environment.NewLine;
                    txtBoxLegacyApp.Text = "";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while sending the data. " + ex.Message,
                    "Legacy Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void DisplayReceiveData(object sender, EventArgs e)
        {
            txtBoxRemoteServ.Text += "> " + displayString.Trim() + Environment.NewLine;

        }
        public void SetErrorText(object sender, EventArgs e)
        {
            if (error != "")
                throw new Exception(error);

        }
        private void txtBoxLegacyApp_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtBoxLegacyApp.Text))
                btnSend.Enabled = false;
            else
                btnSend.Enabled = true;

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] portNames = SerialPort.GetPortNames();
            foreach (string port in portNames)
            {
                if (!cmbPortName.Items.Contains(port))
                    cmbPortName.Items.Add(port);
            }
        }
    }
}